import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:love_app/common/su.dart';
import 'package:love_app/providers/share_provider.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

// 情侣闹钟页面
class LoveAlarm extends StatefulWidget {
  @override
  _LoveAlarmState createState() => _LoveAlarmState();
}

class _LoveAlarmState extends State<LoveAlarm>
    with TickerProviderStateMixin {
  String time; // 当前时间
  String todayDate; // 当前日期
  String weekDay; // 星期几

  Animation<double> animation; // 动画
  AnimationController controller; // 动画控制器

  Status sleepStatus; // 睡觉的状态
  ShareProvider _shareProvider;

  @override
  void initState() {
    _startAnimation(); // 启动动画
    _sleepStatus(); // 初始化睡觉状态
    super.initState(); // 共享数据
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _shareProvider = Provider.of<ShareProvider>(context, listen: false);
  }

  // 一定要销毁动画
  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  // 初始化sleep状态
  void _sleepStatus() async {
    final prefs = await SharedPreferences.getInstance();
    bool isSleep = prefs.getBool('isSleep');
    if (isSleep == null || isSleep == false) {
      _setGetUp();
    } else {
      _setSleeping();
    }
  }

  // 动画
  void _startAnimation() {
    // 动画初始化
    controller = new AnimationController(
      duration: const Duration(seconds: 3),
      vsync: this,
    );
    animation = Tween(begin: 1.0, end: 10.0).animate(controller)
      ..addListener(() {
        setState(() {});
      });
    animation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        //动画执行结束时反向执行动画
        controller.reverse();
      } else if (status == AnimationStatus.dismissed) {
        //动画恢复到初始状态时执行动画（正向）
        controller.forward();
      }
    });
    //启动动画(正向执行)
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {
    _setTime(); // 初始化时间
    return Container(
      decoration: BoxDecoration(
        // 背景图片，可能需要动态获取
        image: DecorationImage(
          image: AssetImage('images/more_page/naozhong_open.png'),
          fit: BoxFit.fill,
        ),
      ),
      child: _body(),
    );
  }

  // 初始化时间
  void _setTime() {
    DateTime today = DateTime.now();
    setState(() {
      time = today.minute < 10
          ? '${today.hour}:0${today.minute}'
          : '${today.hour}:${today.minute}'; // 当前时间,
      todayDate = '${today.month}月${today.day}日'; // 当前日期
      weekDay = "星期" + Su().suNumToString(today.weekday); // 星期几
    });
  }

  // 主体部分
  Widget _body() {
    return Container(
      color: sleepStatus == Status.sleeping
          ? Color.fromRGBO(0, 18, 72, 0.4)
          : Color.fromRGBO(0, 18, 72, 0),
      child: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          _today(), // 日期部分
        ],
      ),
    );
  }

  // 当前时间
  Widget _today() {
    return Positioned(
      top: ScreenUtil().setHeight(215),
      child: Column(
        children: <Widget>[
          _nowTimeText(),
          _dateWeekText(),
          _headers(),
          _buttomWidget(),
        ],
      ),
    );
  }

  // 现在时间的文字格式
  Widget _nowTimeText() {
    return Text(
      time,
      textAlign: TextAlign.center,
      style: TextStyle(
          color: Colors.white,
          fontSize: ScreenUtil().setSp(108),
          fontWeight: FontWeight.w300,
          decoration: TextDecoration.none),
    );
  }

  // 现在日期的文字及样式
  Widget _dateWeekText() {
    String _dateWeek = todayDate + '  ' + weekDay;
    return Text(
      _dateWeek,
      style: Su().textStyle(Color.fromRGBO(204, 204, 204, 1), 24),
    );
  }

  // 头像部分
  Widget _headers() {
    // 是否需要动态边框
    double borderWidth = sleepStatus == Status.sleeping
        ? animation.value
        : ScreenUtil().setWidth(10);
    return Container(
      margin: EdgeInsets.only(
        top: ScreenUtil().setHeight(78),
      ),
      child: Row(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.only(
              right: ScreenUtil().setWidth(79),
            ),
            child: _headerStyle(
              Color.fromRGBO(254, 186, 214, 1),
              _shareProvider.headerImage,
              sleepStatus,
              borderWidth,
            ),
          ),
          _headerStyle(
            Color.fromRGBO(186, 221, 254, 1),
            _shareProvider.loverInfo.headimg,
            Status.getUp,
            ScreenUtil().setWidth(10),
          ),
        ],
      ),
    );
  }

  // 头像样式
  Widget _headerStyle(
      Color borderColor, String imgUrl, Status status, double borderWidth) {
    String _textStatus = status == Status.getUp ? '清醒中' : '睡觉中';
    return Column(
      children: <Widget>[
        Container(
          width: ScreenUtil().setWidth(149),
          height: ScreenUtil().setWidth(149),
          margin: EdgeInsets.only(
            bottom: ScreenUtil().setHeight(27),
          ),
          decoration: BoxDecoration(
            // 头像带颜色的边框
            border: Border.all(
              color: borderColor,
              width: borderWidth, // 边框需要时动画的
            ),
            color: Colors.white,
            borderRadius: BorderRadius.all(
              Radius.circular(
                ScreenUtil().setWidth(90),
              ),
            ),
          ),
          child: _headerStyleChildImage(imgUrl),
        ),
        Text(
          _textStatus,
          style: Su().textStyle(Color.fromRGBO(204, 204, 204, 1), 26),
        ),
      ],
    );
  }

  // 图片样式
  Widget _headerStyleChildImage(String img) {
    return Container(
      padding: EdgeInsets.all(ScreenUtil().setWidth(5)),
      // child: Image.network(img),
      child: ClipOval(
        child: Image.network(
          img,
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  // 两个按钮
  Widget _buttomWidget() {
    return Container(
      margin: EdgeInsets.only(
        top: ScreenUtil().setHeight(64),
      ),
      child: Row(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(
              right: ScreenUtil().setWidth(70),
            ),
            child: _leftButtom(),
          ),
          _rightButtom(),
        ],
      ),
    );
  }

  // 左边的按钮
  Widget _leftButtom() {
    String _button = sleepStatus == Status.sleeping ? '睡觉中' : '我睡了';
    return FlatButton(
      onPressed: () async {
        // 通过读取本地存储，看看是否处于睡觉中
        // 然后修改状态
        final prefs = await SharedPreferences.getInstance();
        bool isSleep = prefs.getBool('isSleep');
        if (isSleep == true) {
          // 起床
          _setGetUp();
        } else {
          // 睡觉
          _setSleeping();
        }
      },
      color: Color.fromRGBO(241, 255, 60, 1),
      padding: EdgeInsets.only(
        left: ScreenUtil().setWidth(84),
        right: ScreenUtil().setWidth(84),
        top: ScreenUtil().setHeight(30),
        bottom: ScreenUtil().setHeight(30),
      ),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(
          ScreenUtil().setWidth(43),
        ),
      ),
      child: Text(
        _button,
        style: Su().textStyle(Color.fromRGBO(86, 86, 86, 1), 28),
      ),
    );
  }

  // 右边的按钮
  Widget _rightButtom() {
    return FlatButton(
      onPressed: () {},
      color: Color.fromRGBO(255, 255, 255, 1),
      padding: EdgeInsets.only(
        left: ScreenUtil().setWidth(84),
        right: ScreenUtil().setWidth(84),
        top: ScreenUtil().setHeight(30),
        bottom: ScreenUtil().setHeight(30),
      ),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(
          ScreenUtil().setWidth(43),
        ),
      ),
      child: Text(
        '叫醒他',
        style: Su().textStyle(Color.fromRGBO(86, 86, 86, 1), 28),
      ),
    );
  }

  // 设置为睡觉中模式
  void _setSleeping() async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setBool('isSleep', true);
    setState(() {
      sleepStatus = Status.sleeping;
    });
  }

  // 设置为清醒中模式
  void _setGetUp() async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setBool('isSleep', false);
    setState(() {
      sleepStatus = Status.getUp;
    });
  }
}

// 状态
enum Status {
  sleeping,
  getUp,
}
